package com.videoweb.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.videoweb.annotation.Anonymous;
import com.videoweb.entity.Category;
import com.videoweb.entity.vo.categoryVo;
import com.videoweb.service.ICategoryService;
import com.videoweb.utils.AjaxResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lmr
 * @since 2025-05-17
 */

@RestController
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    ICategoryService categoryService;

    @GetMapping("/getCategory")
//    @GetMapping("/info")   category/get
    public AjaxResult getCategoryList(){
        List<Category> categories = categoryService.getAllCategory();

        AjaxResult result =AjaxResult.success();

        List<categoryVo> voList = categories.stream()
                .map(category -> {
                    categoryVo vo = new categoryVo();  // 修正类名首字母大写（假设类名为CategoryVo）
                    BeanUtils.copyProperties(category, vo);
                    return vo;
                })
                .collect(Collectors.toList());
        return AjaxResult.success(voList);


//        return categories.stream()
//                .map(category -> {
//                    categoryVo vo = new categoryVo();
//                    BeanUtils.copyProperties(category, vo); // 注意顺序：目标在前
//                    return vo;
//                })
//                .collect(Collectors.toList());

    }

    // 分页查询分类
    @GetMapping("/page")
    public AjaxResult page(@RequestParam(defaultValue = "1") int pageNum,
                           @RequestParam(defaultValue = "10") int pageSize) {
        Page<Category> page = new Page<>(pageNum, pageSize);
        categoryService.page(page);
        return AjaxResult.success(page);
    }

    // 查询单个分类
    @GetMapping("/{id}")
    public AjaxResult getById(@PathVariable Long id) {
        Category category = categoryService.getById(id);
        return AjaxResult.success(category);
    }

    // 新增分类
    @PostMapping
    public AjaxResult add(@RequestBody Category category) {
        boolean ok = categoryService.save(category);
        return ok ? AjaxResult.success("添加成功") : AjaxResult.error("添加失败");
    }

    // 修改分类
    @PutMapping
    public AjaxResult update(@RequestBody Category category) {
        boolean ok = categoryService.updateById(category);
        return ok ? AjaxResult.success("修改成功") : AjaxResult.error("修改失败");
    }

    // 删除分类
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable Long id) {
        boolean ok = categoryService.removeById(id);
        return ok ? AjaxResult.success("删除成功") : AjaxResult.error("删除失败");
    }

}
